package com.michael.demos.base.leetcode;

/**
 * 类功能描述:
 * <pre>
 *   xxxx
 * </pre>
 *
 * @author Michael
 * @version 1.0
 * @date 2020/9/23 10:28
 */
public class Solution2 {

    public static void main(String[] args) {
        ListNode2 l1 = initData(new int[]{2, 4, 3,6});
        ListNode2 l2 = initData(new int[]{5, 6, 4,6});

        Solution2 solution = new Solution2();
        ListNode2 result = solution.addTwoNumbers(l1, l2);
        result.printAll();
    }

    public static ListNode2 initData(int[] arr) {
        ListNode2 result = new ListNode2(arr[0]);
        ListNode2 current = null;
        for (int i = 1; i < arr.length; i++) {
            if (current == null) {
                current = result;
            }
            current.next = new ListNode2(arr[i]);
            current = current.next;
        }
        return result;
    }

    public ListNode2 addTwoNumbers(ListNode2 l1, ListNode2 l2) {
        ListNode2 dummyHead = new ListNode2(-1), pre = dummyHead;
        int t = 0;
        while (l1 != null || l2 != null || t != 0) {
            if (l1 != null) {
                t += l1.val;
                l1 = l1.next;
            }
            if (l2 != null) {
                t += l2.val;
                l2 = l2.next;
            }
            pre.next = new ListNode2(t % 10);
            pre = pre.next;
            t /= 10;
        }

        return dummyHead.next;
    }
}

class ListNode2 {

    int val;
    ListNode2 next;

    ListNode2(int x) { val = x; }

    public void printAll() {

        System.out.print("[" + val + " -> ");

        ListNode2 node = next;
        while (node != null) {
            if (node.next != null) {
                System.out.print(node.val + " -> ");
            } else {
                System.out.println(node.val + "]");
            }
            node = node.next;
        }
    }
}
